<template>
  <div class="tags-add">
    <el-dialog
    :title="`${data.id?'修改':'新增'}标签`"
    :visible.sync="show"
    width="400px">
      <el-form ref="form" size="small" label-width="80px" :model="formModel" :rules="formRules">
        <el-form-item label="所属标签"  prop="subjectID">
          <el-select v-model="formModel.subjectID" style="width:100%">
            <el-option
              v-for="item in subjectOptions"
              :value="item.value"
              :label="item.label"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="formModel.tagName" placeholder="请输入标签名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="show=false">取消</el-button>
        <el-button @click="confirm()" type="primary">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { add, update, simple } from '@/api/hmmm/tags'
export default {
  name: 'TagsAdd',
  data () {
    return {
      show: false,
      formModel: {
        id: null,
        subjectID: null,
        tagName: null
      },
      formRules: {
        subjectID: [
          { type: 'number', message: '请选择所属标签', tirgger: 'blur' }
        ],
        tagName: [
          { required: true, message: '请输入标签名称', tirgger: 'blur' }
        ]
      },
      subjectOptions: []
    }
  },
  props: {
    data: {
      type: Object,
      // 因为父组件currTag为空对象
      // 父子组件传值时default不能直接定义成空数组或空对象，需要用工厂函数return返回一个默认值
      // 这是因为引擎识别 { } 是函数作用域而非对象，加了小括号引擎就可以识别
      default: () => {}
    }
  },
  async created () {
    // 标签下拉选项
    const { data: subjectArr } = await simple()
    this.subjectOptions = subjectArr
  },
  methods: {
    open () {
      // 修改回显
      this.show = true
      // 判断data里的id
      if (this.data.id) {
        console.log('222', this.data)
        // 把data里对应的值赋值给对象
        const { id, subjectID, tagName } = this.data
        // 再次赋值
        this.formModel = { id, subjectID, tagName }
      } else {
        this.formModel = {
          id: null,
          subjectID: +this.$route.query.id || null,
          tagName: null
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    async confirm () {
      // 预校验
      this.$refs.form.validate(async valid => {
        if (valid) {
          // 提交
          if (!this.data.id) {
            // 新增
            await add(this.formModel)
          } else {
            // 修改
            this.formModel.id = this.data.id
            await update(this.formModel)
          }
          this.$message.success('操作成功')
          this.show = false
          this.$emit('updateList')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
